package com.coder.network.request

import android.util.Log
import okhttp3.ResponseBody
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

/**
 * 文件保存
 *
 * @author yuhushuan
 * @date 2017/8/18 10:41
 */
object DownloadUtil {
    private const val tag = "DownloadManager"
    fun writeCache(responseBody: ResponseBody, file: File): File {
        Log.e(tag, "writeCache")
        if (!file.parentFile.exists()) {
            file.parentFile.mkdirs()
        }
        var inputStream: InputStream? = null
        val buffer = ByteArray(1024 * 8)
        var len: Int
        var sum: Long = 0
        var fileOutputStream: FileOutputStream? = null
        inputStream = responseBody.byteStream()
        try {
            fileOutputStream = FileOutputStream(file)
            while (inputStream.read(buffer).also { len = it } != -1) {
                sum += len.toLong()
                fileOutputStream.write(buffer, 0, len)
                Log.e(tag, "sum:$sum")
            }
            fileOutputStream.flush()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            responseBody.close()
            try {
                inputStream?.close()
                fileOutputStream!!.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return file
    }
}